package main

import (
	"fmt"
	"gitee.com/DonHz/simple-blog-system/handler"
	"gitee.com/DonHz/simple-blog-system/util/stringx"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

const (
	COOKIE_NAME = "DonHz"
)

var (
	//loggedIn = make(map[string]string, 1000)
)

func main() {
	r:=gin.Default()
	r.LoadHTMLFiles("account.html", "manage.html")
	r.GET("/login",Login)
	r.GET("/account", Auth, Account)
	r.GET("/manage", Auth, Manage)
	r.Run("localhost:5678")
}

func Manage(ctx *gin.Context) {
	//uid:=getUidFromCookie(ctx)
	//if uid==""{
	//	handler.ReturnError(ctx, 5, "身份校验失败，请重新登录")
	//	return
	//}
	ctx.HTML(http.StatusOK, "manage.html", gin.H {
		"name": COOKIE_NAME,
		"uid": ctx.GetString("uid"),
	})
}

func Account(ctx *gin.Context) {
	//uid:=getUidFromCookie2(ctx)
	//if uid==""{
	//	handler.ReturnError(ctx, 5, "身份校验失败，请重新登录")
	//	return
	//}
	ctx.HTML(http.StatusOK, "account.html", gin.H {
		"name": COOKIE_NAME,
		"uid": ctx.GetString("uid"),
	})
}

func Login(ctx *gin.Context) {
	uid:="1"
	//name:="DonHz"
	key:= stringx.RandStringRunes(20)
	//loggedIn[key] = uid
	SetCookieAuth(key, uid)
	fmt.Println("cookie value: ", key)
	ctx.SetCookie(
		COOKIE_NAME,
		key,
		3600*24*3,	//生命周期
		"/",	//cookie存放目录
		"localhost",
		false,	// 是否只能通过https访问
		true)
	handler.ReturnSuccess(ctx, 200, "success", "", 1)
}

func getUidFromCookie(ctx *gin.Context) string {
	for _, cookie:=range strings.Split(ctx.Request.Header.Get("cookie"),";"){
		arr:=strings.Split(cookie,"=")
		key:=strings.TrimSpace(arr[0])
		value:=strings.TrimSpace(arr[1])
		fmt.Println("key: ",key, ", vaulue: ", value)
		if key == COOKIE_NAME {
			//if uid, exists:=loggedIn[value]; exists {
			if uid:=GetCookieAuth(value); uid!=""{
				return uid
			}
		}
	}
 	return ""
}

func getUidFromCookie2(ctx *gin.Context) string {
	for _, cookie:=range ctx.Request.Cookies() {
		fmt.Println(cookie.Name, cookie.Value)
		if cookie.Name == COOKIE_NAME {
			//if uid, exists:=loggedIn[cookie.Value]; exists {
			if uid:=GetCookieAuth(cookie.Value); uid!=""{
				return uid
			}
		}
	}
	return ""
}

